package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.Orders;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.JwtUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RequestMapping("/user/order")
@Api(tags = "用户订单接口")
@RestController
public class UserOrderController {

    @Autowired
    private OrderService orderService;



    /**
     * 取消订单
     * @param id
     * @return
     */
    @ApiOperation("取消订单")
    @GetMapping("/cancel/{id}")
    public Result cancelOrderById(@PathVariable Integer id){
        orderService.cancelOrderById(id);
        return Result.success();
    }

    /**
     * 历史分页订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @ApiOperation("历史分页订单查询")
    @GetMapping("/historyOrders")
    public Result<PageResult> getHistoryOrders(@RequestBody OrdersPageQueryDTO ordersPageQueryDTO,@RequestHeader("authentication") String authorizationHeader){
        String token = authorizationHeader.replace("Bearer ", "");
        Long userId;

        JwtProperties jwtProperties  = new JwtProperties();
        try {
            // 解析 JWT，以获取用户信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  // 解析 JWT
            userId = claims.get(JwtClaimsConstant.USER_ID, Long.class);
        } catch (Exception e) {
            // 返回错误处理的信息，例如 Token 无效、解析失败等
            return Result.error("无效的 token: " + e.getMessage());
        }

        PageResult pageResult = orderService.getPage(ordersPageQueryDTO,userId);
        return Result.success(pageResult);
    }


    /**
     * 再来一单
     * @param id
     * @return
     */
    @ApiOperation("再来一单")
    @PostMapping("/repetition/{id}")
    public Result repetitionOrder(@PathVariable Integer id){
        orderService.repetitionOrder(id);
        return Result.success();
    }


    //TODO 催单业务没完成
    /**
     * 催单
     * @param id
     * @return
     */
    @GetMapping("/reminder/{id}")
    @ApiOperation("催单")
    public Result reminderOrder(@PathVariable Integer id){

        return Result.success();
    }

    /**
     *查询订单详情
     * @param id
     * @return
     */
    @ApiOperation("查询订单详情")
    @GetMapping("orderDetail/{id}")
    public Result<Orders> getOrderDetail(@PathVariable Integer id){
        return Result.success(orderService.FindById(id));
    }

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @PostMapping("/submit")
    @ApiOperation("用户下单")
    public Result<OrderSubmitVO> submitOrder(@RequestBody OrdersSubmitDTO ordersSubmitDTO,
                                             @RequestHeader("authentication") String authorizationHeader){
        String token = authorizationHeader.replace("Bearer ", "");
        Long userId;

        JwtProperties jwtProperties  = new JwtProperties();
        try {
            // 解析 JWT，以获取用户信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  // 解析 JWT
            userId = claims.get(JwtClaimsConstant.USER_ID, Long.class);
        } catch (Exception e) {
            // 返回错误处理的信息，例如 Token 无效、解析失败等
            return Result.error("无效的 token: " + e.getMessage());
        }

       OrderSubmitVO orderSubmitVO =  orderService.submitOrder(ordersSubmitDTO,userId);
        return Result.success(orderSubmitVO);
    }

    @ApiOperation("订单支付")
    @PutMapping("/payment")
    public Result<String> payment(@RequestBody OrdersPaymentDTO ordersPaymentDTO){
        LocalDateTime payment = orderService.payment(ordersPaymentDTO);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedPayment = payment.format(formatter);
        return Result.success(formattedPayment);
    }
}
